package servlet;

import bean.User;
import db.DbFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/users.do")
public class UserListServlet extends HttpServlet {

    private List<User> users;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            users = DbFactory.getUserDao().find();
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendError(503);
            return;
        }

//        <style>
//                table,table tr th, table tr td { border:1px solid #0094ff; }
//        table { width: 200px; min-height: 25px; line-height: 25px; text-align: center; border-collapse: collapse;}
//    </style>
        String style = "<style>table,table tr th, table tr td { border:1px solid #0094ff; }table { width: 200px; min-height: 25px; line-height: 25px; text-align: center; border-collapse: collapse;}" +
                "</style>";
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<html><head>" + style + "<title>所有用户</title></head></html>");
        out.println("<body><table><td>ID</td><td>用户名</td><td>密码</td><td>手机</td>");
        users.stream().forEach(user -> {
            out.print("<tr><td>" + user.getId() + "</td><td>" + user.getUsername() + "</td><td>" +
                    user.getPass() + "</td><td>" + user.getPhone() + "</td></tr>");
        });

        out.println("</table></body>");
    }
}
